package com;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;

public class MybatisUtil {
    private static SqlSessionFactory sqlSessionFactory;
    static {
        //SqlSessionFactoryBuilder来读取mybatis-config文件来构建会话
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        try(InputStream inputStream = Resources.getResourceAsStream("mybatis.config.xml")){
            sqlSessionFactory = builder.build(inputStream);
        }catch (IOException e){
            e.printStackTrace();
        }
    }
    //这里用static是因为为了方便，直接可以用类名来调用该方法了
    public static SqlSession getSession(){
        return sqlSessionFactory.openSession(true);//事务自动提交true
    }
}
